package com.study.talk.app;

import android.app.DatePickerDialog;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.databinding.ActivityRegisterBinding;
import com.study.talk.entity.resp.RegisterHttpResponse;
import com.study.talk.entity.vo.UserInfoVo;
import com.study.talk.net.NetApi;
import com.study.talk.util.DateUtil;
import com.study.talk.net.OkHttp;
import com.study.talk.util.FileUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.VerificationUtil;

import java.util.Calendar;

import io.netty.util.internal.StringUtil;

public class RegisterActivity extends BaseActivity {

    private UserInfoVo userInfoRequest;
    private ActivityResultLauncher<Uri> takePhoto;
    private ActivityResultLauncher<PickVisualMediaRequest> selectPhoto;
    private ActivityRegisterBinding activityRegisterBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityRegisterBinding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(activityRegisterBinding.getRoot());
        setSupportActionBar(activityRegisterBinding.registerToolbar);
        selectPhoto = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                uploadImage(FileUtil.getPathFromUri(this, uri));
            }
        });
        takePhoto = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
            if (result) {
                uploadImage(FileUtil.getPathFromUri(this, uri));
            }
        });
        initView();
    }


    private void initView() {

        activityRegisterBinding.registerToolbar.setNavigationOnClickListener(v -> finish());

        userInfoRequest = new UserInfoVo();

        activityRegisterBinding.registerImg.setOnClickListener(view -> showSelectPhotoDialog(selectPhoto, takePhoto));

        activityRegisterBinding.registerBirth.setOnClickListener(view -> {
            DatePickerDialog dialog = new DatePickerDialog(RegisterActivity.this);
            dialog.show();
            dialog.setOnDateSetListener((datePicker, year, month, day) -> {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                userInfoRequest.setBirth(DateUtil.DateFormat.format(calendar.getTime()));
                activityRegisterBinding.registerBirth.setText(userInfoRequest.getBirth());
            });
        });

        activityRegisterBinding.registerBt.setOnClickListener(view -> {
            if (checkInput(activityRegisterBinding.registerUsername, "请输入用户名")) return;
            if (checkInput(activityRegisterBinding.registerPassword, "请输入密码")) return;
            if (checkInput(activityRegisterBinding.registerPasswordEnsure, "请输入确认密码"))
                return;
            if (checkInput(activityRegisterBinding.registerNickName, "请输入昵称")) return;
            if (checkInput(activityRegisterBinding.registerPhone, "请输入手机号码")) return;
            if (checkInput(activityRegisterBinding.registerEmail, "请输入邮箱")) return;
            if (checkInput(activityRegisterBinding.registerAddress, "请输入住址")) return;
            if (checkInput(activityRegisterBinding.registerIntroduce, "请输入简介")) return;
            if (userInfoRequest.getAvatar() == null || StringUtil.isNullOrEmpty(userInfoRequest.getAvatar())) {
                ToastUtil.showToast(this, "请上传头像");
            }


            if (VerificationUtil.isValidContent(editTrim(activityRegisterBinding.registerUsername))) {
                ToastUtil.showToast(RegisterActivity.this, "账号名由数字、字母、下划线组成");
                return;
            }

            if (editTrim(activityRegisterBinding.registerPassword).length() < 6 || editTrim(activityRegisterBinding.registerPassword).length() > 18) {
                ToastUtil.showToast(RegisterActivity.this, "密码必须大于等于6且小于等于18位");
                return;
            }

            if (VerificationUtil.isValidEmailAddress(editTrim(activityRegisterBinding.registerEmail))) {
                ToastUtil.showToast(RegisterActivity.this, "请输入正确的邮箱");
                return;
            }

            if (VerificationUtil.isValidTelNumber(editTrim(activityRegisterBinding.registerPhone))) {
                ToastUtil.showToast(RegisterActivity.this, "请输入正确的手机号码");
                return;
            }


            userInfoRequest.setUsername(editTrim(activityRegisterBinding.registerUsername));
            userInfoRequest.setPassword(editTrim(activityRegisterBinding.registerPassword));

            if (!editTrim(activityRegisterBinding.registerPasswordEnsure).equals(userInfoRequest.getPassword())) {
                ToastUtil.showToast(RegisterActivity.this, "两次密码不一致");
                return;
            }

            userInfoRequest.setNickName(editTrim(activityRegisterBinding.registerNickName));
            userInfoRequest.setPhone(editTrim(activityRegisterBinding.registerPhone));
            userInfoRequest.setEmail(editTrim(activityRegisterBinding.registerEmail));
            userInfoRequest.setAddress(editTrim(activityRegisterBinding.registerAddress));
            userInfoRequest.setIntroduce(editTrim(activityRegisterBinding.registerIntroduce));

            if (userInfoRequest.getBirth() == null) {
                ToastUtil.showToast(RegisterActivity.this, "请选择生日");
                return;
            }

            userInfoRequest.setGender(activityRegisterBinding.genderGroup.getCheckedRadioButtonId() == R.id.register_man_bt ? 1 : 0);

            userInfoRequest.setBgImg("");

            OkHttp.post("/user/register", GsonInstance.instance.toJson(userInfoRequest), res -> {
                RegisterHttpResponse response = GsonInstance.instance.fromJson(res, RegisterHttpResponse.class);
                if (response.getStatus() == 200) {
                    runOnUiThread(() -> {
                        ToastUtil.showToast(RegisterActivity.this, "注册成功");
                        finish();
                    });
                } else {
                    runOnUiThread(() -> ToastUtil.showToast(RegisterActivity.this, response.getMessage()));
                }
            });

        });

    }


    public void uploadImage(String path) {
        showLoadingDialog();
        NetApi.uploadImage(path, RegisterActivity.this, data -> {
            userInfoRequest.setAvatar(data);
            runOnUiThread(() -> {
                Glide.with(RegisterActivity.this).load(OkHttp.URL + data).into(activityRegisterBinding.registerImg);
                ToastUtil.showToast(RegisterActivity.this, "头像上传成功！");
            });
        }, msg -> runOnUiThread(() -> ToastUtil.showToast(RegisterActivity.this, msg)));
    }
}